<?php

namespace App\Http\Controllers\Api;

use App\Models\LiveMeetingRoom;
use App\Models\LiveMeetingRoomUser;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class MeetingController extends Controller
{

    protected $http = '';
    public function __construct()
    {
        $this -> http = new Client();
    }

    /**
     * 直播间信息
     * @param Request $request
     */
    public function meetingInfo(Request $request)
    {
        $room_id = $request -> input('room_id');
        if(!$room_id){
            return jsonError('请输入房间号');
        }

        $liveMeetingRoom = LiveMeetingRoom::with(['meeting_admin:id,username,name,avatar']) -> where('room_no',$room_id) -> first();

        if($liveMeetingRoom){
            $liveMeetingRoom -> meeting_user = User::select(['id','user_name','real_name','head_portrait']) -> where('id',auth() -> id()) -> first();

            $liveMeetingRoom -> meeting_user->user_name  =  $liveMeetingRoom->meeting_user -> real_name ?: $liveMeetingRoom->meeting_user->user_name;
            $liveMeetingRoom -> meeting_user->head_portrait_url = img_url($liveMeetingRoom -> meeting_user -> head_portrait);

            unset($liveMeetingRoom -> meeting_user -> real_name);
        }


        return jsonSuccess($liveMeetingRoom);

    }



    public function checkRoomSecret(Request $request){

        $room_id = $request -> input('room_id');
        $room_secret = $request -> input('room_secret');

        $message = [
            'room_id.required' => '请输入房间号',
            'room_secret.required' => '请输入密钥'
        ];
        $validator = Validator::make($request -> all(),[
            'room_id' => 'required',
            'room_secret' => 'required'
        ],$message);

        if($validator -> fails()){
            return jsonError($validator -> messages() -> first());
        }


        // 判断房间和密钥是否正确
        $liveMeetingRoom = LiveMeetingRoom::where(['room_no' => $room_id, 'room_secret' => $room_secret]) -> first();
        if($liveMeetingRoom){

            return jsonSuccess();
        }else{
            return jsonError('请输入正确的房间号 或 密钥');
        }

    }


    /**
     * 登陆直播间
     * @param Request $request
     */
    public function meetingOperate(Request $request)
    {
        $room_id = $request -> input('room_id');
        $type = $request -> input('type');
        $message = [
            'room_id.required' => '请输入房间号',
            'type.required' => '请选择操作类型',
        ];
        $validator = Validator::make($request -> all(),[
            'room_id' => 'required',
            'type' => 'required'
        ],$message);

        if($validator -> fails()){
            return jsonError($validator -> messages() -> first());
        }



        // 判断房间和密钥是否正确
        $liveMeetingRoom = LiveMeetingRoom::where(['room_no' => $room_id]) -> first();
        if($liveMeetingRoom){

            $user_id = auth() -> id();
            switch($type){
                case 1:

                    if($liveMeetingRoom -> online_user_num >= $liveMeetingRoom -> room_num_limit){
                        return jsonError('该房间已达人数上限');
                    }
                    $liveMeetingRoomUser = LiveMeetingRoomUser::where(['user_id' => $user_id,'room_no' => $room_id]) -> first();
                    if($liveMeetingRoomUser){


                        if($liveMeetingRoomUser -> status == 1){
                            return jsonSuccess($liveMeetingRoomUser);
                        }else{

                            // 核对token是否过期，过期就重新换一个
                            if($liveMeetingRoomUser -> token_expiration_time < date('Y-m-d H:i:s')){

                                $user_no = $liveMeetingRoomUser -> room_user_no;
                                $token = get_zego_token($room_id, $user_no);
                                $liveMeetingRoomUser -> token = $token;
                                $liveMeetingRoomUser -> token_expiration_time = date('Y-m-d H:i:s', (time() + 3600));
                            }

                            $liveMeetingRoomUser -> status = 1;
                            $liveMeetingRoomUser -> last_login_time = date('Y-m-d H:i:s');


                            $res = $liveMeetingRoomUser -> save();
                            if($res){
                                $liveMeetingRoom -> online_user_num = LiveMeetingRoomUser::where('room_no',$room_id) ->where('status',1) -> count();
                                $liveMeetingRoom -> save();
                                return jsonSuccess($liveMeetingRoomUser);
                            }
                        }

                    }else{

                        $user_no = 'xiangtong_'.rand_str(6);

                        $token = get_zego_token($room_id, $user_no);

                        $data = [
                            'meeting_id'              => $liveMeetingRoom -> id,
                            'user_id'                 => auth() -> id(),
                            'room_user_no'            => $user_no,
                            'room_no'                 => $room_id,
                            'audio_publish_stream_id' => 'audio_'.rand_str(4),
                            'token'                   => $token,
                            'token_expiration_time'   => date('Y-m-d H:i:s', (time() + 3600)),
                            'last_login_time'         => date('Y-m-d H:i:s'),
                            'status'                  => 1

                        ];
                        $liveMeetingRoomUser = LiveMeetingRoomUser::create($data);

                        if($liveMeetingRoomUser){

                            $liveMeetingRoom -> online_user_num = LiveMeetingRoomUser::where('room_no',$room_id) ->where('status',1) -> count();
                            $liveMeetingRoom -> save();
                            return jsonSuccess($liveMeetingRoomUser);
                        }

                    }

                    break;
                case 2:

                    $liveMeetingRoomUser = LiveMeetingRoomUser::where('room_no',$room_id) -> where('user_id',$user_id) -> where('status',1) -> first();

                    if ($liveMeetingRoomUser) {
                        $liveMeetingRoomUser -> status = 0;
                        $liveMeetingRoomUser -> mike_status = 0;
                        $liveMeetingRoomUser -> time_long += time() - strtotime($liveMeetingRoomUser -> last_login_time);


                        $live = $liveMeetingRoomUser -> save();

                        if($live){
                            $liveMeetingRoom -> online_user_num = LiveMeetingRoomUser::where('room_no',$room_id) ->where('status',1) -> count();
                            $liveMeetingRoom -> save();
                            return jsonSuccess(2008);
                        }
                    } else {
                        return jsonError(4045);
                    }

                    break;
                case 3:

                    $liveMeetingRoomUser = LiveMeetingRoomUser::where(['user_id' => $user_id,'room_no' => $room_id,'status' => 1]) -> first();
                    if($liveMeetingRoomUser){
                        $liveMeetingRoomUser -> mike_status = 1;
                        $res = $liveMeetingRoomUser -> save();

                        if($res){
                            return jsonSuccess();
                        }

                        return jsonError();
                    }else{
                        return jsonError(4046);
                    }
                    break;
                case 4:

                    $liveMeetingRoomUser = LiveMeetingRoomUser::where(['user_id' => $user_id,'room_no' => $room_id,'status' => 1]) -> first();
                    if($liveMeetingRoomUser){
                        $liveMeetingRoomUser -> mike_status =  0;
                        $res = $liveMeetingRoomUser -> save();

                        if($res){
                            return jsonSuccess();
                        }

                        return jsonError();
                    }else{
                        return jsonError(4046);
                    }
                    break;
            }

        }else{
            return jsonError('请输入正确的房间号');
        }

    }



    /**
     * 获取用户列表
     * @param Request $request
     */
    public function getRoomUserList(Request $request)
    {
        $room_id = $request -> input('room_id');
        $Mode    = $request -> input('Mode') ?: 0;

        $message = [
            'room_id.required' => '请输入房间号',
        ];
        $validator = Validator::make($request -> all(),[
            'room_id' => 'required',
        ],$message);

        if($validator -> fails()){
            return jsonError($validator -> messages() -> first());
        }


        $roomUserList = LiveMeetingRoomUser::with(['user_info:id,user_name,real_name,head_portrait'])
            -> where('room_no',$room_id)
            -> where('status',1)
            -> orderBy('last_login_time',($Mode ? 'desc' : 'asc')) -> get(['id','user_id','last_login_time','status','mike_status']);

        foreach ($roomUserList as $roomUserListVal) {

            $roomUserListVal -> last_login_time = substr($roomUserListVal -> last_login_time,11,5);
            $roomUserListVal -> user_info->user_name = $roomUserListVal -> user_info->real_name ?: $roomUserListVal -> user_info->user_name;
            $roomUserListVal -> user_info->head_portrait_url = img_url($roomUserListVal -> user_info->head_portrait);

            unset($roomUserListVal -> user_info->real_name);
        }



        return jsonSuccess($roomUserList);
    }


    /**
     * 获取房间总人数
     */
    public function getRoomUserNum(Request $request)
    {
        $roomId = $request -> input('room_id');

        if(!$roomId){
            return jsonError('请输入房间号');
        }

        $count = LiveMeetingRoomUser::where('room_no',$roomId) -> where('status',1) -> count();

        return jsonSuccess(['UserCountList' => ['RoomId' => $roomId,'UserCount' => $count]]);



        /*$url   = "https://rtc-api.zego.im/?Action=DescribeUserNum";
        $param = "&RoomId[]=".$roomId;

        // $url 与参数组合
        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;
        $res = $this -> http -> get($url);

        $result = json_decode($res->getBody()->getContents(),true);
        if ($result['Message'] == 'success') {
            return jsonSuccess($result['Data']);
        }

        return jsonSuccess();*/
    }


    /**
     * 房间踢人
     * @param Request $request
     * @return false|string
     */
    public function roomGetOut(Request $request)
    {
        $room_id   = $request -> input('room_id');
        $user_ids  = $request -> input('user_ids');

        if(!$room_id){
            return jsonError('请输入房间号');
        }

        $user_ids_arr = explode(',',$user_ids);
        if(!$user_ids_arr){
            return jsonError('请输入用户编号');
        }


        $roomGetout = LiveMeetingRoomUser::roomGetOut($room_id,$user_ids_arr);


        if($roomGetout){
            $liveMeetingRoomUser = LiveMeetingRoomUser::where('room_no',$room_id)
                -> whereIn('room_user_no',$user_ids_arr) -> update(['status' => 2]);

            if($liveMeetingRoomUser){
                $count = LiveMeetingRoomUser::where('room_no',$room_id) ->where('status',1) -> count();
                LiveMeetingRoom::where('room_no',$room_id) -> update(['online_user_num' => $count]);

                return jsonSuccess(2007);
            }
        }

        return jsonError();

    }


    /**
     * 增加房间流
     * @param Request $request
     */
    public function addStream(Request $request)
    {
        $room_id = $request -> input('room_id');
        $user_id = $request -> input('user_id');
        $stream_id = $request -> input('stream_id');

        $url   = "https://rtc-api.zego.im/?Action=AddStream";
        $param = "&RoomId=".$room_id
            .'&UserId='.$user_id
            .'&StreamId='.$stream_id;


        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;


        $addStream = $this -> http -> get($url);
        $result = json_decode($addStream->getBody()->getContents(),true);
        if ($result['Message'] == 'success') {
            return jsonSuccess();
        }

        return jsonError();
    }


    /**
     * 删除房间流
     * @param Request $request
     */
    public function delStream(Request $request)
    {
        $room_id = $request -> input('room_id');
        $user_id = $request -> input('user_id');
        $stream_id = $request -> input('stream_id');

        $url   = "https://rtc-api.zego.im/?Action=DeleteStream";
        $param = "&RoomId=".$room_id
            .'&UserId='.$user_id
            .'&StreamId='.$stream_id;


        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;


        $addStream = $this -> http -> get($url);
        $result = json_decode($addStream->getBody()->getContents(),true);
        if ($result['Message'] == 'success') {
            return jsonSuccess();
        }

        return jsonError();
    }


    /*  -------------------------回调  start---------------------------  */
    /** 登陆房间回调
     *  @return string
     */
    public function loginRoomBack(Request $request)
    {

        /* {
             "user_account": "888120154",
             "user_nickname": "888120154",
             "session_id": "0",
             "room_id": "rid_1242649",
             "room_seq": "6085791336856668982",
             "room_name": "room#123",
             "login_time": 1499676978027,
             "timestamp": 1499676978,
             "nonce": "350176",
             "signature": "signature"
         }*/


        $user_no = $_POST['user_account'];
        $room_id = $_POST['room_id'];
        $login_time =$_POST['login_time'];



        $liveMeetingRoomUser = LiveMeetingRoomUser::where(['room_user_no' => $user_no,'room_no' => $room_id]) -> first();
        if($liveMeetingRoomUser){

            $liveMeetingRoomUser -> status = 1;
            $liveMeetingRoomUser -> last_login_time = date('Y-m-d H:i:s',substr($login_time,0, 10));

            $res = $liveMeetingRoomUser -> save();
            if($res){
                return json_encode(['code' => 200]);
            }
        }

    }


    /**退出房间回调
     * @param Request $request
     * @return string
     */
    public function logoutRoomBack(Request $request)
    {
        /* {
             "user_account": "888120154",
             "user_nickname": "888120154",
             "session_id": "0",
             "room_id": "rid_1242649",
             "room_seq": "6085791336856668982",
             "logout_time": 1499676978027,
             "timestamp": 1499676978,
             "nonce": "350176",
             "signature": "signature"
         }*/

        $user_no = $_POST['user_account'];
        $room_id = $_POST['room_id'];
        $logout_time = $_POST['logout_time'];



        $liveMeetingRoomUser = LiveMeetingRoomUser::where('room_no',$room_id) -> where('room_user_no',$user_no) -> where('status',1) -> first();

        if($liveMeetingRoomUser){
            $liveMeetingRoomUser -> status = 0;
            $liveMeetingRoomUser -> mike_status = 0;
            $liveMeetingRoomUser -> time_long += substr($logout_time,0,10) - strtotime($liveMeetingRoomUser -> last_login_time);


            $live = $liveMeetingRoomUser -> save();

            if($live){

                return json_encode(['code' => 200]);
            }
        }


    }

    /**流创建回调
     * @param Request $request
     */
    public function streamCreateBack(Request $request)
    {
        $backParam = $_POST;




    }
    /*  -------------------------回调  end---------------------------  */


    /**开始音频审核
     * @param Request $request
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function startCensorAudio(Request $request)
    {

        $room_id = $request -> input('room_id');
        $stream_id = $request -> input('stream_id');
        $audioType = $request -> input('audioType/a');


        // 规则验证
        $message = [
            'stream_id.required' => '请输入用户编号',
            'room_id.required'   => '请输入房间号',
            'audioType.required' => '请选择审核类型',
        ];
        $validator = Validator::make($request -> all(),[
            'room_id' => 'required',
            'stream_id' => 'required',
            'audioType' => 'required',
        ],$message);

        if($validator -> fails()){
            return jsonError($validator -> messages() -> first());
        }


        // $url组合
        $url   = "https://rtc-api.zego.im/?Action=StartCensorAudio";
        $param = "&RoomId=".$room_id
            .'&StreamId='.$stream_id;
        foreach($audioType as $v){
            $param .= '&AudioType[]='.$v;
        }


        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;


        // https get请求
        $startCensorAudio = $this -> http -> get($url);
        $result = json_decode($startCensorAudio->getBody()->getContents(),true);
        if ($result['Message'] == 'success') {
            return jsonSuccess($result['Data']);
        }

        return jsonError();
    }


    /**停止音频审核
     * @param Request $request
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function stopCensorAudio(Request $request)
    {
        $taskId = $request -> input('task_id');

        if(!$taskId){
            return jsonError();
        }

        $url = "https://rtc-api.zego.im/?Action=StopCensorAudio";
        $param = "&TaskId=".$taskId;

        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;

        // https get请求
        $stopCensorAudio = $this -> http -> get($url);
        $result = json_decode($stopCensorAudio->getBody()->getContents(),true);
        if ($result['Message'] == 'success') {
            return jsonSuccess();
        }

        return jsonError();
    }


    /**
     * 开始视频流审核
     * @param Request $request
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function startCensorVideo(Request $request)
    {
        $room_id    = $request -> input('room_id');
        $stream_id  = $request -> input('stream_id');
        $imageType  = $request -> input('imageType/a');
        $audioType  = $request -> input('audioType/a');

        $detectFrequency = $request -> input('detectFrequency');
        $detectStep      = $request -> input('detectStep');


        // 规则验证
        $message = [
            'room_id.required'    => '请输入房间号',
            'stream_id.required'  => '请输入用户编号',
            'imageType.required'  => '请选择视频审核类型',
            'audioType.required'  => '请选择音频审核类型',
            'detectFrequency.required' => '请输入视频流截帧频率',
            'detectStep.required' => '请输入视频流截帧图片检测步长',
        ];
        $validator = Validator::make($request -> all(),[
            'room_id'    => 'required',
            'stream_id'  => 'required',
            'imageType'  => 'required',
            'audioType'  => 'required',
            'detectFrequency' => 'required',
            'detectStep' => 'required',
        ],$message);

        if($validator -> fails()){
            return jsonError($validator -> messages() -> first());
        }




        $url = "https://rtc-api.zego.im/?Action=StartCensorVideo";
        $param = "&RoomId=".$room_id
            .'&Stream_id='.$stream_id;

        foreach($imageType as $v){
            $param .= "&ImageType[]=".$v;
        }

        foreach($audioType as $vo){
            $param .= "&AudioType[]=".$vo;
        }

        $param = $param
            ."&DetectFrequency=".$detectFrequency
            ."&DetectStep=".$detectStep;



        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;


        // https get请求
        $startCensorVideo = $this -> http -> get($url);
        $result = json_decode($startCensorVideo->getBody()->getContents(),true);
        if ($result['Message'] == 'success') {
            return jsonSuccess($result['Data']);
        }

        return jsonError();


    }


    /**介素视频流审核
     * @param Request $request
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function stopCensorVideo(Request $request)
    {
        $taskId = $request -> input('task_id');
        if(!$taskId){
            return jsonError('请输入任务id');
        }


        $url = "https://rtc-api.zego.im/?Action=StopCensorVideo";
        $param = "&TaskId=".$taskId;


        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;

        $stopCensorVideo = $this -> http -> get($url);
        $result = json_decode($stopCensorVideo -> getBody()->getContents(),true);
        if( $result['message'] == 'success' ){
            return jsonSuccess();
        }

        return jsonError();

    }


    /**
     * 获取简易流
     * @param Request $request
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getSimpleStreamList(Request $request)
    {
        $room_id = $request -> input('room_id');

        if(!$room_id){
            return jsonError('请输入房间号');
        }

        $url = "https://rtc-api.zego.im/?Action=DescribeSimpleStreamList";
        $param = "&RoomId=".$room_id;

        $common_param = LiveMeetingRoom::commonParam();
        $url = $url.$param.'&'.$common_param;

        $simpleStreamList = $this -> http -> get($url);
        $result = json_decode($simpleStreamList ->getBody() ->getContents(), true);
        if ($result['Message'] == 'success') {
            return jsonSuccess($result['Data']);
        }

        return jsonError();

    }

}
